package com.app.service.impl;

import com.alibaba.excel.EasyExcel;
import com.app.controller.importExcel.ImportExcelListener;
import com.app.mapper.TestFailureMapper;
import com.app.model.DepartmentModel;
import com.app.model.TestFailureModel;
import com.app.service.DepartmentService;
import com.app.service.TestFailureService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TestFileUtil;
import com.app.vo.TestFailureVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.ListUtils;
import org.thymeleaf.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class TestFailureServiceImpl implements TestFailureService {
    @Autowired
    private TestFailureMapper testFailureMapper;
    @Autowired
    private DepartmentService departmentService;

    @Override
    public void update(TestFailureModel testFailureModel) {
        testFailureMapper.updateById(testFailureModel);
    }

    @Override
    public void insert(TestFailureModel testFailureModel) {
        testFailureMapper.insert(testFailureModel);
    }

    @Override
    public TestFailureVo getTestFailureList(Integer page, Integer limit, String name, Integer departmentId, Integer sortType) {
        Page<TestFailureModel> page1 = new Page<>();
        page1.setCurrent(page);
        page1.setSize(limit);
        QueryWrapper<TestFailureModel> queryWrapper = new QueryWrapper<>();
        if (name != null && !name.equals("")) {
            queryWrapper.eq("task_name", name);
        }
        if (departmentId != null) {
            queryWrapper.eq("department_id", departmentId);
        }
        if (sortType==null || sortType==1){
            queryWrapper.orderByAsc("number").orderByDesc("create_time");
        }else {
            queryWrapper.orderByDesc("number").orderByDesc("create_time");
        }
        Page<TestFailureModel> testFailureModelPage = testFailureMapper.selectPage(page1, queryWrapper);
        for (int i = 0; i < testFailureModelPage.getRecords().size(); i++) {
            if (testFailureModelPage.getRecords().get(i).getDepartmentId() != null) {
                DepartmentModel departmentModel = departmentService.getDepByDepId(testFailureModelPage.getRecords().get(i).getDepartmentId());
                if (departmentModel != null) {
                    testFailureModelPage.getRecords().get(i).setDepartmentName(departmentModel.getName());//获取部门名字
                }
            }
            if (testFailureModelPage.getRecords().get(i).getIsUse() == 1) {
                testFailureModelPage.getRecords().get(i).setIsUseText("是");
            } else {
                testFailureModelPage.getRecords().get(i).setIsUseText("否");
            }
        }
        TestFailureVo vo = new TestFailureVo();
        vo.setList(testFailureModelPage.getRecords());
        vo.setCount((int) testFailureModelPage.getTotal());
        return vo;
    }

    @Override
    public void deleteTestFailure(Integer id) {
        testFailureMapper.deleteById(id);
    }

    @Override
    public TestFailureModel getModelById(Integer id) {
        return testFailureMapper.selectById(id);
    }

    @Override
    public List<TestFailureModel> getPlantByIds(List<Integer> appIdList) {
        QueryWrapper<TestFailureModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().in("id", appIdList);
        return testFailureMapper.selectList(queryWrapper);
    }

    // 导入实验故障统计excel文件
    @Override
    public String importTestFaultFile(MultipartFile file) throws Exception {
        List<String> errorList = new ArrayList<>();
        String path = TestFileUtil.getPath() + "excel.xlsx";
        File localFile = new File(path);
        file.transferTo(localFile);
        String filePath = localFile.getAbsolutePath();
        AtomicReference<Integer> row = new AtomicReference<>(0);
        try {
            EasyExcel.read(filePath, TestFailureModel.class, new ImportExcelListener<TestFailureModel>(dataList -> {
                for (TestFailureModel testFailureModel : dataList) {
                    DepartmentModel departmentModel = departmentService.getdepByName(testFailureModel.getDepartmentName());
                    if (testFailureModel.getIsUseText().equals("是")) {
                        testFailureModel.setIsUse(1);
                    } else {
                        testFailureModel.setIsUse(0);
                    }
                    if (departmentModel == null) {
                        testFailureModel.setCreateTime(CommonHelp.getNowTimestamp());
                        testFailureMapper.insert(testFailureModel);
                    } else {
                        testFailureModel.setDepartmentId(departmentModel.getId());
                        testFailureModel.setCreateTime(CommonHelp.getNowTimestamp());
                        testFailureMapper.insert(testFailureModel);
                        row.set(row.get() + 1);
                    }
                }
            }, errorList)).sheet().headRowNumber(1).doRead();
        } catch (Exception e) {
            e.printStackTrace();
            return "Excel导入失败";
        }
        localFile.delete();
        if (row.get() == 0) {
            return "导入0条，请检查模版或者数据格式";
        }
        StringBuilder msg = new StringBuilder("成功导入" + row + "行。");
        if (errorList.size() != 0) {
            for (String error : errorList) {
                msg.append(error);
            }
        }
        return msg.toString();
    }

    /**
     * 批量删除失败的实验数据
     * @param ids
     * @return
     */
    @Override
    public Result<Object> deleteBatchByIds(String ids) {
        // 参数校验
        if (StringUtils.isEmpty(ids)) {
            return Result.success("参数为空，无需删除");
        }
        List<Integer> idsList = Arrays.stream(ids.split(","))
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        // 批量删除
        if (!ListUtils.isEmpty(idsList)) {
            testFailureMapper.deleteBatchIds(idsList);
            return Result.success("批量删除成功");
        } else {
            return Result.success("批量删除失败，数据为空");
        }
    }
}
